'use strict';

function _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }

// ==UserScript==
// @name         okex-auto-trade
// @namespace    https://gitee.com/adams549659584/res/tree/master/src/tampermonkey/okex
// @version      1.0.0
// @description  okex 自动交易
// @author       罗君
// @match        *://www.okex.com/spot/trade
// @require      https://adams549659584.gitee.io/res/dist/gm-layui/layui.js?t=201805211154
// @resource     frm-okex-setting http://adams549659584.gitee.io/res/dist/gm-layui/template/frm-okex-setting.html?t=201805211154
// @resource     raw-websocket http://adams549659584.gitee.io/res/dist/tampermonkey/okex/raw-websocket.js?t=201805211154
// @resource     new-websocket http://adams549659584.gitee.io/res/dist/tampermonkey/okex/new-websocket.js?t=201805211154
// @grant GM_getResourceText
// @grant GM_getResourceURL
// @grant unsafeWindow
// @run-at document-start
// ==/UserScript==

(function () {
    'use strict';

    // console.log(document.head);

    var newWebsocketUrl = GM_getResourceURL('new-websocket');
    // console.log(`newWebsocketUrl:${newWebsocketUrl}`);
    var newWebsocketScript = document.createElement('script');
    newWebsocketScript.type = 'text/javascript';
    newWebsocketScript.src = newWebsocketUrl;
    document.head.appendChild(newWebsocketScript);

    function taskRun(func) {
        var _arguments = arguments;

        return new Promise(function (resolve, reject) {
            if (typeof func !== 'function') {
                reject('\u51FD\u6570\u6709\u8BEF');
                return;
            }
            setTimeout(function () {
                try {
                    var thatArgs = [].concat(Array.prototype.slice.call(_arguments));
                    var funcArgs = thatArgs.splice(1);
                    resolve(func.apply(undefined, _toConsumableArray(funcArgs)));
                } catch (error) {
                    reject(error);
                }
            }, 0);
        });
    }

    var diffPrice = 0.1;
    var okexAsks = new Map();
    var okexBids = new Map();
    var okexAskPrices = [];
    var okexBidPrices = [];
    var isFirstLoad = true;

    var calcDepth = function calcDepth(res) {
        if (isFirstLoad) {
            //sell
            var sellListLi = document.querySelectorAll('.sell-list li');
            for (var i = 0, len = sellListLi.length; i < len; i++) {
                var sellLi = sellListLi[i];
                var sellPrice = Number(sellLi.children[0].innerHTML.replace(/,/, ''));
                var sellTotalSize = Number(sellLi.children[1].innerHTML.replace(/,/, ''));
                if (sellTotalSize > 0) {
                    okexAsks.set(sellPrice, sellTotalSize);
                }
            }
            okexAskPrices = Array.from(okexAsks.keys()).sort();
            //buy
            var buyListLi = document.querySelectorAll('.buy-list li');
            for (var _i = 0, _len = buyListLi.length; _i < _len; _i++) {
                var buyLi = buyListLi[_i];
                var buyPrice = Number(buyLi.children[0].innerHTML.replace(/,/, ''));
                var buyTotalSize = Number(buyLi.children[1].innerHTML.replace(/,/, ''));
                if (buyTotalSize > 0) {
                    okexBids.set(buyPrice, buyTotalSize);
                }
            }
            okexBidPrices = Array.from(okexBids.keys()).sort();
        }
        var data = res.data;
        taskRun(function () {
            if (data.asks && data.asks.length > 0) {
                for (var _i2 = 0, _len2 = data.asks.length; _i2 < _len2; _i2++) {
                    var ask = data.asks[_i2];
                    var price = Number(ask.price);
                    var totalSize = Number(ask.totalSize);
                    if (totalSize === 0) {
                        okexAsks.delete(price);
                    } else {
                        okexAsks.set(price, totalSize);
                    }

                    okexAskPrices = Array.from(okexAsks.keys()).sort();
                    var thatDiffPrice = (okexAskPrices[0] * 10000 - okexBidPrices[okexBidPrices.length - 1] * 10000) / 10000;
                    if (thatDiffPrice >= diffPrice) {
                        var thatBidPrice = okexBidPrices[okexBidPrices.length - 1];
                        var thatBidSize = okexBids.get(thatBidPrice);
                        var thatAskPrice = okexAskPrices[0];
                        var thatAskSize = okexAsks.get(thatAskPrice);
                        console.log('\u4E70\u5165\u4EF7:' + thatBidPrice + ',\u6570\u91CF:' + thatBidSize + ',\u5356\u51FA\u4EF7\uFF1A' + thatAskPrice + ',\u6570\u91CF:' + thatAskSize + ',\u5DEE\u4EF7\uFF1A' + thatDiffPrice);
                        console.log(okexAskPrices);
                        console.log(okexBidPrices);
                    }
                }
            }
        });

        taskRun(function () {
            if (data.bids && data.bids.length > 0) {
                for (var _i3 = 0, _len3 = data.bids.length; _i3 < _len3; _i3++) {
                    var bid = data.bids[_i3];
                    var price = Number(bid.price);
                    var totalSize = Number(bid.totalSize);
                    if (totalSize === 0) {
                        okexBids.delete(price);
                    } else {
                        okexBids.set(price, totalSize);
                    }
                    okexBidPrices = Array.from(okexBids.keys()).sort();
                    var thatDiffPrice = (okexAskPrices[0] * 10000 - okexBidPrices[okexBidPrices.length - 1] * 10000) / 10000;
                    if (thatDiffPrice >= diffPrice) {
                        var thatBidPrice = okexBidPrices[okexBidPrices.length - 1];
                        var thatBidSize = okexBids.get(thatBidPrice);
                        var thatAskPrice = okexAskPrices[0];
                        var thatAskSize = okexAsks.get(thatAskPrice);
                        console.log('\u4E70\u5165\u4EF7:' + thatBidPrice + ',\u6570\u91CF:' + thatBidSize + ',\u5356\u51FA\u4EF7\uFF1A' + thatAskPrice + ',\u6570\u91CF:' + thatAskSize + ',\u5DEE\u4EF7\uFF1A' + thatDiffPrice);
                        console.log(okexAskPrices);
                        console.log(okexBidPrices);
                    }
                }
            }
        });
    };

    var resDomain = 'https://adams549659584.gitee.io/res/dist/gm-layui/';
    //配置
    layui.config({
        dir: resDomain, //layui.js 所在路径（注意，如果是script单独引入layui.js，无需设定该参数。），一般情况下可以无视
        version: false, //一般用于更新模块缓存，默认不开启。设为true即让浏览器不缓存。也可以设为一个固定的值，如：201610
        debug: false, //用于开启调试模式，默认false，如果设为true，则JS模块的节点会保留在页面
        base: '/res/gm-layui/' //设定扩展的Layui模块的所在目录，一般用于外部模块扩展
    });
    layui.use(['util', 'layer', 'form'], function () {
        var util = layui.util;
        var $ = layui.jquery;
        var layer = layui.layer;
        var form = layui.form;
        // $(function () {
        //     const websocketScriptName = 'websocket.js';
        //     const lastWebsocketScriptSrc = 'https://img.bafang.com/cdn/exv1/20180509200029/spot/libs/websocket.js';

        //     for (let i = 0; i < document.scripts.length; i++) {
        //         const thatScript = document.scripts[i];
        //         console.log(`thatScript.src:${thatScript.src}`);
        //         if (thatScript.src.includes(websocketScriptName)) {
        //             //TODO 存原始的websocket 与 最新的比较
        //             //TODO 替换逻辑处理
        //             $(thatScript).before('<script type="text/javascript" src="https://adams549659584.gitee.io/res/dist/tampermonkey/okex/new-websocket.js"></script>').remove();
        //             break;
        //         }
        //     }
        // });
        //添加样式
        $('head').append('<link rel="stylesheet" href="' + resDomain + 'css/layui.css">');
        //固定块
        util.fixbar({
            bar1: '&#xe631;',
            css: {
                top: 100,
                right: 10
            },
            bgcolor: '#0096df',
            click: function click(type) {
                var self = this;
                if (type === "bar1") {
                    var ws = OK_GLOBAL.ws;
                    // const ws = new WebSocketUtil();
                    if (ws.isInjected) {
                        //页面层
                        var formHtml = GM_getResourceText('frm-okex-setting');
                        layer.open({
                            title: '配置',
                            type: 1,
                            skin: 'layui-layer-rim', //加上边框
                            area: '800px', //宽高
                            content: formHtml
                        });
                        form.render();
                    } else {
                        layer.confirm('脚本注入失败，是否刷新重新注入', {
                            btn: ['刷新', '算了'] //按钮
                        }, function () {
                            location.reload();
                            return;
                        }, function () {
                            //移除配置
                            $(self).parent().remove();
                        });
                    }
                }
            }
        });
    });

    //全局
    unsafeWindow.calcDepth = calcDepth;
})();